var clickSubmit = false;//是否点击了保存
layui.config({
    base: baseUrl + '/js/layui/module/'
}).extend({//设定模块别名
    treeSelect: 'treeSelect/treeSelect',//static/js/layui/module/treeSelect/treeSelect.js
    formSelects: 'formSelects/formSelects-v4',//static/js/layui/module/formSelects/formSelects-v4.js
    dtree : 'dtree/dtree'
});
layui.use(['form','layer','laydate','table','laytpl','element','formSelects'],function(){
    var element = layui.element;
    var laydate = layui.laydate;
    var form = layui.form,
        layer=layui.layer;
    $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;
    currentIndex = parent.layer.getFrameIndex(window.name);//获取当前窗体索引

    var formSelects = layui.formSelects;
    formSelects.btns('hadIndustryTypeIds', ['select', 'remove', 'reverse']);
    formSelects.data('hadIndustryTypeIds', 'local', {
        // url: baseUrl + '/industryType/queryByTree?type=treeNode&selVal='+speakingPackage.hadIndustryTypeId,
        arr : treeMap
    });

    /*formSelects.render('hadIndustryTypeIds',{
        height: "150px"                //是否固定高度, 38px | auto
    });*/

    formSelects.on('hadIndustryTypeIds', function(id, vals, val, isAdd, isDisabled){
        //id:           点击select的id
        //vals:         当前select已选中的值
        //val:          当前select点击的值
        //isAdd:        当前操作选中or取消
        //isDisabled:   当前选项是否是disabled
        //如果return false, 那么将取消本次操作
        return true;
    });



    //添加话术包
    form.on('submit(add)', function(formData){
        //弹出loading
        try{
            if(clickSubmit == true){//防重复提交
                return;
            }
            clickSubmit = true;
            var load = window.parent.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
            var bo = verification(formData.form,null);
            if(bo){
                var submitData = formData.field;
                saveData(submitData,load);
            }else{
                window.parent.layer.close(load);
            }
        }catch (e){
            window.parent.layer.msg('操作异常');
        }finally {
            clickSubmit = false;
        }

    });

    function saveData(submitData,load){
        $.ajax({
            type: "POST",
            url:  baseUrl+'/flowConfig/saveSpeakingPackage',
            dataType: 'json',
            data: submitData,
            success: function (data) {
                console.log(data);
                window.parent.layer.close(load);
                if(data.code<=0){
                    layer.msg(data.msg);
                }else{
                    layer.msg("保存成功");
                    //关闭本窗体
                    setTimeout(function () {
                        parent.reloadTable();
                        $("#cancel").click();
                    },1000);
                }
            },
            error: function () {
                window.parent.layer.close(load);
                layer.msg("保存失败");
                return ;
            }
        });
    }

    $('#cancel').on('click',function () {
        parent.layer.close(currentIndex);//执行关闭
    });

    //验证表单
    function verification(form,iframeWin) {
        var config = {
            verify: {
                required: [
                    /[\S]+/
                    , '必填项不能为空'
                ]
                , phone: [
                    /^1\d{10}$|^$/
                    , '请输入正确的手机号'
                ]
                , email: [
                    /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$|^$/
                    , '邮箱格式不正确'
                ]
                , url: [
                    /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/
                    , '链接格式不正确'
                ]
                , number: [
                    /^\d+$|^$/
                    , '只能填写数字'
                ]
                , date: [
                    /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$|^$/
                    , '日期格式不正确'
                ]
                , identity: [
                    /(^\d{15}$)|(^\d{17}(x|X|\d)$|^$)/
                    , '请输入正确的身份证号'
                ]
            }
        };
        formElem = $(form);
        var button = $(this), verify = config.verify, stop = null
            , DANGER = 'layui-form-danger',PROMPT='required_prompt', field = {}
            , verifyElem = formElem.find('*[lay-verify-zdy]') //获取需要校验的元素
            , checkedElem = formElem.find('*[data-required]') //获取复选框
            ,rangeElem = formElem.find('*[data-range]')//获取范围判断的区间值

        //开始校验
        layui.each(verifyElem, function (_, item) {
            var othis = $(this), tips = '';
            var arr = othis.attr('lay-verify-zdy').split(',');
            for (var i in arr) {
                var ver = arr[i];
                var value = othis.val(), isFn = typeof verify[ver] === 'function';
                if(ver == 'number'&&value==''){
                    value = 0;
                }
                othis.removeClass(DANGER);
                if (verify[ver] && (isFn ? tips = verify[ver](value, item) : !verify[ver][0].test(value))) {
                    layer.msg(tips || verify[ver][1], {
                        icon: 5
                        , shift: 6
                    });
                    //非移动设备自动定位焦点
                    if (!layui.device().android && !layui.device().ios) {
                        if(item.type=='text'){
                            item.focus();
                        }else if(item.type=="select-one"){
                            $(item).next("div").find("input").focus();
                            $(item).next("div").find("input").attr("readonly");
                        }
                    }
                    othis.addClass(DANGER);
                    return stop = true;
                }
            }
        });
        if (stop) return false;
        //返回序列化表单元素， JSON 数据结构数据。
        return true;
    }
});